<template>
  <div ref="rightPanel" class="rightPanel-container">
    <div class="rightPanel-background"></div>
    <div class="rightPanel">
      <div class="rightPanel-items">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, useTemplateRef } from 'vue'
import { useStore } from 'vuex'

const props = defineProps({
  clickNotClose: {
    default: false,
    type: Boolean,
  },
})

const store = useStore()

const show = computed({
  get() {
    return store.state.settings.showSettings
  },
  set(val) {
    store.dispatch('settings/changeSetting', {
      key: 'showSettings',
      value: val,
    })
  },
})

const rightPanel = useTemplateRef('rightPanel')

let clickEventListenerAdded = false

const addEventClick = () => {
  if (!clickEventListenerAdded) {
    window.addEventListener('click', closeSidebar)
    clickEventListenerAdded = true
  }
}

const closeSidebar = (evt: any) => {
  const parent = evt.target.closest('.el-drawer__body')
  if (!parent) {
    show.value = false
    window.removeEventListener('click', closeSidebar)
    clickEventListenerAdded = false
  }
}

watch(show, (value) => {
  if (value && !props.clickNotClose) {
    addEventClick()
  }
})

onMounted(() => {
  addEventClick()
})

onBeforeUnmount(() => {
  // 确保在组件销毁前移除事件监听器
  window.removeEventListener('click', closeSidebar)
  clickEventListenerAdded = false

  // 安全地移除DOM元素
  if (rightPanel.value) {
    rightPanel.value.remove()
  }
})
</script>

<style lang="scss" scoped>
.rightPanel-background {
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  background: rgba(0, 0, 0, 0.2);
  z-index: -1;
}

.rightPanel {
  width: 100%;
  max-width: 260px;
  height: 100vh;
  position: fixed;
  top: 0;
  right: 0;
  box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.05);
  transition: all 0.25s cubic-bezier(0.7, 0.3, 0.1, 1);
  transform: translate(100%);
  background: #fff;
  z-index: 40000;
}

.handle-button {
  width: 48px;
  height: 48px;
  position: absolute;
  left: -48px;
  text-align: center;
  font-size: 24px;
  border-radius: 6px 0 0 6px !important;
  z-index: 0;
  pointer-events: auto;
  cursor: pointer;
  color: #fff;
  line-height: 48px;
  i {
    font-size: 24px;
    line-height: 48px;
  }
}
</style>
